 # coding=utf-8
'''
Created on Jun 1, 2009

@author: tdelev
'''
from datetime import *
import logging
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import memcache

logging.getLogger().setLevel(logging.DEBUG)

class User(db.Model):
    user = db.UserProperty()
    display_name = db.StringProperty()
    date_joined = db.DateTimeProperty(auto_now_add = True)
    date_last_seen = db.DateTimeProperty(auto_now = True)
    
    def __unicode__(self):
        return self.display_name
    
    @staticmethod
    def get_user(user):
        users = User.all().filter('user = ', user).fetch(1)
        if len(users) <= 0:
            u = User(user = user, display_name = 'unknown')
            u.put()
            return u
        return users[0]
    
    @staticmethod
    def get_all():
        users = User.all().fetch(1000)
        return users

class UserProfile(db.Model):
    user = db.ReferenceProperty(User)    
    email = db.EmailProperty()
    real_name = db.StringProperty()
    web_site = db.LinkProperty()
    location = db.StringProperty()
    birthday = db.DateProperty()
    about_me = db.TextProperty()
    
    @staticmethod
    def get_all():
        parts = memcache.get('parts')
        if parts is not None:
            return parts
        else:
            parts = Part.all().fetch(6)
            if not memcache.add('parts', parts, 600):
                logging.error("Memcache set failed for parts.")    
            return parts
        
    @staticmethod
    def clear_cache():
        memcache.delete('parts')
            
    
class Question(db.Model):
    user = db.ReferenceProperty(User)
    title = db.StringProperty(required = True)
    description = db.TextProperty(required = True)
    tags = db.StringListProperty(required = True)
    date_posted = db.DateTimeProperty(auto_now_add = True)
    date_edited = db.DateTimeProperty(auto_now = True)
    answered = db.BooleanProperty(default = False)
    votes = db.IntegerProperty(default = 0)    
    views = db.IntegerProperty(default = 0)
    answers = db.IntegerProperty(default = 0)
    bounty = db.IntegerProperty(default = 0)
    
    def __unicode__(self):        
        return self.name
    def desc_short(self):
        return self.description[:140] + '...'
    
    def posted(self):        
        dif = datetime.now() - self.date_posted        
        if dif.days > 7:
            return self.date_posted.strftime('%d %b, %Y')
        else:
            if dif.days > 1:
                return str(dif.days) + u'дена'
            else:
                if dif.seconds > 3600:
                    return str(dif.seconds / 3600) + u' часа'
                else:
                    return str(dif.seconds / 60) + u' минути'
                         
    
    def link(self):
        return self.title.replace(' ', '-').replace('?', '')
        
    def save(self):
        #TODO function for tags spliting
        tags = self.tags[0]
        self.tags = tags.split(' ')
        Tag.update_tags(self.tags)
        return self.put()
    
    @staticmethod
    def get_all(order_by):
        questions = Question.all().order('-%s' % order_by).fetch(1000)
        return questions
    
    @staticmethod
    def get_featured():
        questions = Question.all().filter('bounty > ', 0).fetch(1000)
        return questions
     
    @staticmethod
    def get_unanswered():
        questions = Question.all().filter('answered = ', False).fetch(1000)
        return questions
    
    @staticmethod
    def get_by_tag(tag):
        questions = Question.all().filter('tags = ', tag).fetch(1000)
        return questions 
    
    @staticmethod
    def get_by_id(id):
        question = db.get(db.Key.from_path('Question', id))
        return question 
    
    @staticmethod
    def delete_all():
        questions = Question.all().fetch(1000)
        for q in questions:
            q.delete()
    
    @staticmethod
    def get_by_key(key):
        question = memcache.get(key)
        if question is not None:
            return question
        else:
            question = db.get(db.Key(key))
            if not memcache.add(key, question):
                logging.error("Memcache set failed for question.")    
            return question 
     
class Answer(db.Model):
    question = db.ReferenceProperty(Question)
    user = db.UserProperty(required = True)
    text = db.TextProperty(required = True)
    value = db.IntegerProperty(required=True)
    
    date_posted = db.DateTimeProperty(required = True)
    date_edited = db.DateTimeProperty()
    votes = db.IntegerProperty(default = 0)
        
    def __unicode__(self):
        return self.choice
    
    
class Tag(db.Model):
    name = db.StringProperty(required = True)
    total = db.IntegerProperty(default = 1)
    date_created = db.DateTimeProperty(auto_now_add = True)
        
    def __unicode__(self):
        return self.name
    
    @staticmethod
    def update_tags(tags_list):
        for t in tags_list:
            tags = Tag.all().filter('name = ', t).fetch(1)
            tag = None
            if len(tags) == 0:
                tag = Tag(name = t)
            else:
                tag = tags[0]
                tag.total += 1
            tag.put()
            
            
    @staticmethod
    def get_all():
        tags = Tag.all().fetch(1000)
        return tags 
    
    @staticmethod
    def delete_all():
        tags = Tag.all().fetch(1000)
        for t in tags:
            t.delete() 
